package com.fzf.org.result;

import com.fzf.org.exception.BizException;
import com.fzf.org.exception.BizExceptionTypeEnum;

import java.util.Optional;

public final class Results {
    /**
     * 构造成功响应
     */
    public static Result<Void> success() {
        return new Result<Void>()
                .setCode(Result.SUCCESS_CODE);
    }

    /**
     * 构造带返回数据的成功响应
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>()
                .setCode(Result.SUCCESS_CODE)
                .setData(data);
    }

    /**
     * 构建服务端底层失败响应
     */
    public static Result<Void> failure() {
        return new Result<Void>()
                .setCode(BizExceptionTypeEnum.SERVICE_ERROR.getCode())
                .setMsg(BizExceptionTypeEnum.SERVICE_ERROR.getMsg());
    }

    /**
     * 通过传入的具体的错误构建服务端失败响应
     */
    public static Result<Void> failure(BizException bizException) {
        String errorCode = Optional.ofNullable(bizException.getCode())
                .orElse(BizExceptionTypeEnum.SERVICE_ERROR.getCode());

        String errorMessage = Optional.ofNullable(bizException.getMsg())
                .orElse(BizExceptionTypeEnum.SERVICE_ERROR.getMsg());

        return new Result<Void>()
                .setCode(errorCode)
                .setMsg(errorMessage);
    }

}
